use anyhow::{Result, anyhow};
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use serde_json::Value;
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::Path;
use std::str::FromStr;
use std::sync::mpsc::Receiver;
use std::{fs, thread};

/// 解析请求头
pub(super) fn parse_header(headers: Vec<String>) -> Result<HeaderMap> {
    let mut header_map = HeaderMap::new();
    for header in headers {
        let split = header.split_once(":");
        match split {
            Some((key, value)) => {
                let name = HeaderName::from_str(key.trim())?;
                let value = HeaderValue::from_str(value.trim())?;
                header_map.insert(name, value);
            }
            None => return Err(anyhow!("非法的请求头")),
        }
    }
    Ok(header_map)
}

/// 解析请求头
pub(super) fn parse_header_with_map(headers: HashMap<String, String>) -> Result<HeaderMap> {
    let mut header_map = HeaderMap::new();
    for (key, value) in headers {
        let name = HeaderName::from_str(key.trim())?;
        let value = HeaderValue::from_str(value.trim())?;
        header_map.insert(name, value);
    }
    Ok(header_map)
}

/// 解析form参数
pub(super) fn parse_form(form: Vec<String>) -> Result<HashMap<String, Value>> {
    let mut form_map = HashMap::new();
    for f in form {
        let split = f.split_once("=");
        match split {
            Some((key, value)) => {
                form_map.insert(key.into(), From::from(value));
            }
            None => return Err(anyhow!("表单参数错误")),
        }
    }
    Ok(form_map)
}

/// 解析json参数
pub(super) fn parse_json(json: Option<String>) -> Result<HashMap<String, Value>> {
    if json.is_none() {
        return Ok(HashMap::new());
    }
    let json = serde_json::from_str(&json.unwrap())?;
    Ok(json)
}


/// 将请求结果输出到文件
pub(super) fn output<P: AsRef<Path>>(path: P, rx: Receiver<String>) -> Result<()> {
    let path = path.as_ref();

    // 获取父目录路径
    if let Some(parent) = path.parent() {
        // 如果目录不存在，则创建（包括所有父目录）
        if !parent.exists() {
            fs::create_dir_all(parent)?;
        }
    }
    let file = File::create(path)?;

    thread::spawn(move || {
        let mut writer = BufWriter::new(file);
        while let Ok(data) = rx.recv() {
            writeln!(writer, "{}\n", data).expect("写入文件错误");
        }
        writer.flush().expect("刷新文件错误");
    });

    Ok(())
}